package org.demo.rc;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.Serializable;

/**
 * UDP中传输的数据对象
 * @author  
 * @date    2010-10-22
 * @file    org.demo.rc.UDPImageMessage.java
 */
public class UDPImageMessage implements Serializable{
	/**
	 * 反序列化图像数据
	 * @param buf
	 * @param offset
	 * @param length
	 * @return
	 * @throws IOException
	 */
	public void unpack(byte[] buf,int offset,int length) throws IOException{
		ByteArrayInputStream bis = new ByteArrayInputStream(buf, offset, length);
		DataInputStream in = new DataInputStream(bis);
		// 
		this.md5 = in.readUTF();
		this.size = in.readInt();
		this.index = in.readInt();
		this.time = in.readLong();
		this.data = new byte[in.available()];
		in.read(data);
		// 
		in.close();
	}
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	// 当前图像的 MD5 值 [== md5( md5(image) + time)]
	private String md5;
	// 标识图像由几个包组成
	private int size;
	// 标识当前是第几个包
	private int index;
	// 数据内容
	private byte[] data;
	// 时间戳
	private long time;
	/**
	 * 构造函数
	 */
	public UDPImageMessage(){
	}
	/**
	 * 构造函数
	 * @param md5
	 * @param size
	 * @param index
	 * @param data
	 */
	public UDPImageMessage(String md5,int size,int index,byte[] data){
		this.md5 = md5;
		this.size = size;
		this.index = index;
		this.data = data;
	}
	/**
	 * 打包数据 [容量扩大80个字节]
	 * @return
	 * @throws IOException 
	 */
	public byte[] pack() throws IOException{
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		DataOutputStream out = new DataOutputStream(bos);
		// 
		out.writeUTF(md5);    // 64 = 32*2 byte [每个字符占两个字节]
		out.writeInt(size);   // 4 byte
		out.writeInt(index);  // 4 byte
		out.writeLong(time);  // 8 byte
		out.write(data);
		// 
		out.flush();
		return bos.toByteArray();
	}
	/**
	 * @return the md5
	 */
	public String getMd5() {
		return md5;
	}
	/**
	 * @param md5 the md5 to set
	 */
	public void setMd5(String md5) {
		this.md5 = md5;
	}
	/**
	 * @return the size
	 */
	public int getSize() {
		return size;
	}
	/**
	 * @param size the size to set
	 */
	public void setSize(int size) {
		this.size = size;
	}
	/**
	 * @return the index
	 */
	public int getIndex() {
		return index;
	}
	/**
	 * @param index the index to set
	 */
	public void setIndex(int index) {
		this.index = index;
	}
	/**
	 * @return the data
	 */
	public byte[] getData() {
		return data;
	}
	/**
	 * @param data the data to set
	 */
	public void setData(byte[] data) {
		this.data = data;
	}
	/**
	 * @return the time
	 */
	public long getTime() {
		return time;
	}
	/**
	 * @param time the time to set
	 */
	public void setTime(long time) {
		this.time = time;
	}
}
